package com.whsr.readservice.controller;

import com.github.pagehelper.PageInfo;
import com.whsr.readservice.dto.JobBatchRequest;
import com.whsr.readservice.service.DownBookMaintainService;
import com.whsr.readservice.util.JobThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/server/downbook")
public class DownBookMaintainController {

    @Autowired
    private DownBookMaintainService downBookMaintainService;

    @Autowired
    private ServletContext applicContext;

    @RequestMapping(value = "/downBookJob",method = RequestMethod.GET)
    public Object downBookJob(){
        Map<String, Object> msg = new HashMap<>();
        if(downBookMaintainService.isNoComplateBookIdList()){
            msg.put("msg", "无待办任务，无需启动任务");
        } else {
            Object start = applicContext.getAttribute("start");
            if(start == null){
                applicContext.setAttribute("start", 1);
                new Thread(new JobThread(downBookMaintainService, applicContext)).start();
                msg.put("msg", "任务启动，请稍后查看任务完成情况");
            } else {
                msg.put("msg", "任务正在执行中，无法启动");
            }
        }
        return msg;
    }

    @RequestMapping(value = "/getJobList/{pageNo}/{pageSize}",method = RequestMethod.POST)
    public PageInfo<JobBatchRequest> getJobList(@PathVariable Integer pageNo,
                                                @PathVariable Integer pageSize,
                                                @RequestBody JobBatchRequest JobBatchRequest){
       return downBookMaintainService.getJobList(pageNo, pageSize, JobBatchRequest);
    }


    @RequestMapping(value = "/import",method = RequestMethod.POST)
    public Map<String, Object> importBookIds(MultipartFile file){
        String fileName = file.getOriginalFilename();
        Map<String, Object> msg = null;
        try {
            msg = downBookMaintainService.importBookIds(fileName, file);
        } catch (IOException e) {
            msg = new HashMap<>();
            msg.put("msg", "文件解析失败");
        }
        return msg;
    }



}
